import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/mysql';
import { verifyToken } from '@/lib/auth';

// 标记题目检测状态
export async function POST(request: NextRequest) {
  try {
    // 验证管理员权限
    const token = request.cookies.get('token')?.value;
    if (!token) {
      return NextResponse.json({ error: '未登录' }, { status: 401 });
    }

    const payload = verifyToken(token);
    if (!payload || payload.role !== 'admin') {
      return NextResponse.json({ error: '无权限' }, { status: 403 });
    }

    const userId = payload.userId;
    const body = await request.json();
    const { questionId, topicId, topicName, questionIndex, status, issueType, notes } = body;

    if (!questionId || !topicId || questionIndex === undefined || !status) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    // 插入或更新检测记录
    await db.query(
      `INSERT INTO question_reviews 
       (question_id, topic_id, topic_name, question_index, status, issue_type, notes, reviewed_by, reviewed_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
       ON DUPLICATE KEY UPDATE
         status = VALUES(status),
         issue_type = VALUES(issue_type),
         notes = VALUES(notes),
         reviewed_at = NOW()`,
      [questionId, topicId, topicName, questionIndex, status, issueType || null, notes || null, userId]
    );

    return NextResponse.json({ 
      success: true,
      message: '标记成功'
    });

  } catch (error: any) {
    console.error('标记题目失败:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

